/**
 *  编辑页
 *
 * 作者 admin
 * 日期 2024-08-19 14:13:44
 */
layui.use(['jquery','febs', 'form', 'validate', 'formSelects'], function () {
    var $ = layui.$,
        febs = layui.febs,
        layer = layui.layer,
        form = layui.form,
        laydate = layui.laydate,
        formSelects = layui.formSelects,
        table = layui.table,
        $view = $('#hazardExamine-edit'),
        $addRelation_company = $('#addRelation_company'),
        $addGroup_dept = $view.find("#addGroup_dept"),
        $addGroup_project = $view.find("#addGroup_project"),
        validate = layui.validate,
        tableIns_company,
        panelCount_dept = 0,
        panelCount_project = 0;
    let tenantId = POPUP_DATA.tenantId;
    let groupUserTableData_company = [];

    form.verify(validate);
    initGroupUserTable_company();
    initFormValue();
    form.render();

    function initGroupUserTable_company() {
        tableIns_company = febs.table.init({
            elem: $view.find('#groupUserTable_company'),
            id: 'groupUserTable_company',
            page:false,
            skin: '',
            limit:Number.MAX_VALUE,
            cols: [[
                {title: '序号', type: 'numbers',width: 60},
                {field: 'examineTeamId', title: 'id',hide:true},
                {field: 'teamName',title: '分组名称', minWidth: 220},
                {field: 'teamUserList', title: '检查人员', minWidth: 500, templet: function (d) {
                        var flg = '';
                        var users = d.teamUserList;
                        if(users){
                            users.forEach((item, index)=> {
                                flg += '<span class="layui-badge febs-bg-orange" style="margin-left:5px; ">'+item.realName+'</span>'
                            })
                        }
                        return flg;
                    }
                },
                {title: '操作',align:'center', toolbar: '#group-user-option-company', width: 80},
            ]],
            done: function(res, curr, count){

                // 获取当前行数据 - 自定义方法
                table.getRowData = function(tableId, elem){
                    var index = $(elem).closest('tr').data('index');
                    return table.cache[tableId][index] || {};
                };
            },
            data:groupUserTableData_company
        });
    }

    table.on('tool(groupUserTable_company)', function (obj) {
        var data = obj.data,
            that = this,
            tr = obj.tr,
            layEvent = obj.event;
        if (layEvent === 'del') {
            febs.modal.confirm('删除', '确定删除？', function (index) {
                var cacheData = layui.table.cache['groupUserTable_company'];//获取缓存
                obj.del();//①移除这一行
                var rowIndex = obj.tr.attr("data-index"); //获取行索引
                cacheData.splice(rowIndex, 1);  //②彻底移除元素，从缓存里移除这一行
                groupUserTableData_company = cacheData;
                reloadTab_company(groupUserTableData_company);
                layer.close(index);//关闭弹窗
            });
        }
    });
    function reloadTab_company(data){
        tableIns_company.reload({data:data});
    }

    table.on('tool(groupUserTable_dept)', function (obj) {
        var layEvent = obj.event;
        let idSort = $(this).parents('div.layui-panel').attr('id').slice(10);
        if (layEvent === 'del') {
            febs.modal.confirm('删除','确定删除？', function (index) {
                var cacheData = layui.table.cache['groupUserTable_dept'+idSort];//获取缓存
                obj.del();//①移除这一行
                var rowIndex = obj.tr.attr("data-index"); //获取行索引
                cacheData.splice(rowIndex, 1);  //②彻底移除元素，从缓存里移除这一行
                reloadTable($view.find('#groupUserTable_dept'+idSort),'groupUserTable_dept'+idSort,cacheData);
                layer.close(index);//关闭弹窗
            });
        }
    });

    table.on('tool(groupUserTable_project)', function (obj) {
        var layEvent = obj.event;
        let idSort = $(this).parents('div.layui-panel').attr('id').slice(13);
        if (layEvent === 'del') {
            febs.modal.confirm('删除','确定删除？', function (index) {
                var cacheData = layui.table.cache['groupUserTable_project'+idSort];//获取缓存
                obj.del();//①移除这一行
                var rowIndex = obj.tr.attr("data-index"); //获取行索引
                cacheData.splice(rowIndex, 1);  //②彻底移除元素，从缓存里移除这一行
                reloadTable($view.find('#groupUserTable_project'+idSort),'groupUserTable_project'+idSort,cacheData);
                layer.close(index);//关闭弹窗
            });
        }
    });
    function initGroupUserTable(elem,tableId,tableData) {
        febs.table.init({
            elem: elem,
            id: tableId,
            page:false,
            skin: '',
            limit:Number.MAX_VALUE,
            cols: [[
                {title: '序号', type: 'numbers',width: 60},
                {field: 'examineTeamId', title: 'id',hide:true},
                {field: 'teamName',title: '分组名称', width: 220},
                {field: 'teamUserList', title: '检查人员', minWidth: 500, templet: function (d) {
                        var flg = '';
                        var users = d.teamUserList;
                        if(users){
                            users.forEach((item, index)=> {
                                flg += '<span class="layui-badge febs-bg-orange" style="margin-left:5px; ">'+item.realName+'</span>'
                            })
                        }
                        return flg;
                    }
                },
                {title: '操作',align:'center', toolbar: '#group-user-option-dept', width: 80}
            ]],
            done: function(res, curr, count){

                // 获取当前行数据 - 自定义方法
                table.getRowData = function(tableId, elem){
                    var index = $(elem).closest('tr').data('index');
                    return table.cache[tableId][index] || {};
                };
            },
            data:tableData
        });
    }

    function reloadTable(elem,tableId,tableData){
        initGroupUserTable(elem,tableId,tableData);
    }
    function addRelation_dept(elem,sort){
        $(elem).on('click', function () {
            var groupUserTableData_dept = layui.table.cache['groupUserTable_dept'+sort].length==0?[]:layui.table.cache['groupUserTable_dept'+sort];
            febs.modal.open('增加分组', 'common/hazardExamineTeam', {
                btn: ['确认','关闭'],
                area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
                data:{
                    tenantId:tenantId,
                    selectList:groupUserTableData_dept,
                    multiple:true,
                },
                yes: function (index, layero) {
                    let selectData = null
                    if(typeof getSelectData  === 'function'){
                        selectData = getSelectData()
                    }

                    for (var i = 0; i < selectData.length; i++) {
                        var temp = {};
                        temp.examineTeamId = selectData[i].examineTeamId;
                        temp.tenantId = $("#tenantId").val();
                        temp.teamName = selectData[i].teamName;
                        temp.teamUserList = selectData[i].teamUserList;
                        groupUserTableData_dept.push(temp);
                    }
                    reloadTable($view.find('#groupUserTable_dept'+sort),'groupUserTable_dept'+sort,groupUserTableData_dept);
                    layer.close(index);
                },
                btn2: function (index, layero) {
                    layer.close(index);
                    return false;
                }
            });
        });
    }

    function addRelation_project(elem,sort){
        $(elem).on('click', function () {
            var groupUserTableData_project = layui.table.cache['groupUserTable_project'+sort].length==0?[]:layui.table.cache['groupUserTable_project'+sort];
            febs.modal.open('增加分组', 'common/hazardExamineTeam', {
                btn: ['确认','关闭'],
                area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
                data:{
                    tenantId:tenantId,
                    selectList:groupUserTableData_project,
                    multiple:true,
                },
                yes: function (index, layero) {
                    let selectData = null
                    if(typeof getSelectData  === 'function'){
                        selectData = getSelectData()
                    }

                    for (var i = 0; i < selectData.length; i++) {
                        var temp = {};
                        temp.examineTeamId = selectData[i].examineTeamId;
                        temp.tenantId = $("#tenantId").val();
                        temp.teamName = selectData[i].teamName;
                        temp.teamUserList = selectData[i].teamUserList;
                        groupUserTableData_project.push(temp);
                    }
                    reloadTable($view.find('#groupUserTable_project'+sort),'groupUserTable_project'+sort,groupUserTableData_project);
                    layer.close(index);
                },
                btn2: function (index, layero) {
                    layer.close(index);
                    return false;
                }
            });
        });
    }

    $addRelation_company.on('click', function () {
        febs.modal.open('增加分组', 'common/hazardExamineTeam', {
            btn: ['确认','关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
            data:{
                tenantId:tenantId,
                selectList:groupUserTableData_company,
                multiple:true,
            },
            yes: function (index, layero) {
                let selectData = null
                if(typeof getSelectData  === 'function'){
                    selectData = getSelectData()
                }

                for (var i = 0; i < selectData.length; i++) {
                    var temp = {};
                    temp.examineTeamId = selectData[i].examineTeamId;
                    temp.tenantId = $("#tenantId").val();
                    temp.teamName = selectData[i].teamName;
                    temp.teamUserList = selectData[i].teamUserList;
                    groupUserTableData_company.push(temp);
                }

                reloadTab_company(groupUserTableData_company);
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });

    });

    //增加部门、车间、班组分组信息
    $addGroup_dept.on('click', function () {
        var examineType  = $view.find('select[name="examineType"]').find('option:selected').val();
        var label = '';
        if(examineType =='2'){
            label = '部门名称';
        }else if(examineType =='3'){
            label = '车间名称';
        }else if(examineType =='4'){
            label = '班组名称';
        }
        var groupPanel = '<div class="layui-panel layui-panel-dept" id="panel_dept' + panelCount_dept + '">' +
            '                        <div class="layui-field-box">' +
            '                            <div class="layui-form-item" >' +
            '                                <div class="layui-row">' +
            '                                    <div class="layui-col-md6">' +
            '                                        <label class="layui-form-label" id="deptNameLabel">'+label+'：</label>' +
            '                                        <div class="layui-input-block">' +
            '                                            <select name="deptId_deptExamine" lay-filter="deptId_deptExamine' + panelCount_dept + '" id="deptId_deptExamine' + panelCount_dept + '">' +
            '                                                <option value="">请选择</option>' +
            '                                            </select>' +
            '                                        </div>' +
            '                                    </div>' +
            '                                    <div class="layui-col-md6">' +
            '                                        <div class="layui-input-block">' +
                        '                               <div class="layui-row layui-row-button">' +
                        '                                   <div name="delete" class="layui-btn layui-btn-danger layui-btn-sm">' +
                        '                                       <em class="layui-icon layui-icon-delete"></em> 删除信息' +
                        '                                   </div>' +
                        '                               </div>' +
            '                                        </div>' +
            '                                    </div>' +
            '                                </div>' +
            '                            </div>' +
            '                            <div class="layui-form-item">' +
            '                                <div class="layui-row">' +
            '                                    <label class="layui-form-label">检查人员：</label>' +
            '                                    <div class="layui-input-block">' +
            '                                        <table lay-filter="groupUserTable_dept" id="groupUserTable_dept' + panelCount_dept + '" lay-data="{id: \'groupUserTable_dept\'' + panelCount_dept + '}"></table>' +
            '                                    </div>' +
            '                                </div>' +
            '                            </div>' +
            '                            <div class="layui-form-item">' +
            '                                <div class="layui-row">' +
            '                                    <div class="layui-col-md12">' +
            '                                        <div class="layui-input-block">' +
            '                                            <button type="button" class="layui-btn layui-btn-sm" id="addRelation_dept' + panelCount_dept + '">' +
            '                                                <span class="layui-icon layui-icon-add-1" ></span>检查分组' +
            '                                            </button>' +
            '                                        </div>' +
            '                                    </div>' +
            '                                </div>' +
            '                            </div>' +
            '                        </div>' +
            '                    </div>';
        $("#dept_box").append(groupPanel);
        //增加分组按钮
        addRelation_dept("#addRelation_dept"+panelCount_dept,panelCount_dept);
        //部门下拉框
        initDeptSelect($("#deptId_deptExamine"+panelCount_dept),{tenantId:tenantId});
        //分组人员table
        initGroupUserTable($view.find('#groupUserTable_dept'+panelCount_dept),'groupUserTable_dept'+panelCount_dept,[]);
        form.render();
        panelCount_dept++;

    });


    //增加项目检查分组信息
    $addGroup_project.on('click', function () {
        var groupPanel = '<div class="layui-panel layui-panel-project" id="panel_project' + panelCount_project + '">' +
            '                        <div class="layui-field-box">' +
            '                            <div class="layui-form-item" >' +
            '                                <div class="layui-row">' +
            '                                    <div class="layui-col-md6">' +
            '                                        <label class="layui-form-label">项目名称：</label>' +
            '                                        <div class="layui-input-block">' +
            '                                            <select name="projectName" lay-filter="projectSelect' + panelCount_project + '" id="projectSelect' + panelCount_project + '">' +
            '                                                <option value="">请选择</option>' +
            '                                            </select>' +
            '                                        </div>' +
        '                                        </div>' +
            '                                    <div class="layui-col-md6">' +
            '                                        <div class="layui-input-block">' +
                    '                                    <div class="layui-row layui-row-button">' +
                    '                                       <div name="delete" class="layui-btn layui-btn-danger layui-btn-sm">' +
                    '                                           <em class="layui-icon layui-icon-delete"></em> 删除信息' +
                    '                                       </div>' +
                    '                                    </div>' +
        '                                            </div>' +
            '                                    </div>' +
            '                                </div>' +
            '                            </div>' +
            '                            <div class="layui-form-item">' +
            '                                <div class="layui-row">' +
            '                                    <label class="layui-form-label">检查人员：</label>' +
            '                                    <div class="layui-input-block">' +
            '                                        <table lay-filter="groupUserTable_project" id="groupUserTable_project' + panelCount_project + '" lay-data="{id: \'groupUserTable_project\'' + panelCount_project + '}"></table>' +
            '                                    </div>' +
            '                                </div>' +
            '                            </div>' +
            '                            <div class="layui-form-item">' +
            '                                <div class="layui-row">' +
            '                                    <div class="layui-col-md12">' +
            '                                        <div class="layui-input-block">' +
            '                                            <button type="button" class="layui-btn layui-btn-sm" id="addRelation_project' + panelCount_project + '">' +
            '                                                <span class="layui-icon layui-icon-add-1" ></span>检查分组' +
            '                                            </button>' +
            '                                        </div>' +
            '                                    </div>' +
            '                                </div>' +
            '                            </div>' +
            '                        </div>' +
            '                    </div>';
        $("#project_box").append(groupPanel);
        //增加分组按钮
        addRelation_project("#addRelation_project"+panelCount_project,panelCount_project);
        //项目下拉框
        initProjectSelect($("#projectSelect"+panelCount_project),{tenantId:tenantId});
        //区域下拉框
        // initProjectSelectArea($("#projectAreaSelect" + panelCount_project) ,panelCount_project);
        //分组人员table
        initGroupUserTable($view.find('#groupUserTable_project'+panelCount_project),'groupUserTable_project'+panelCount_project,[]);
        form.render();
        panelCount_project++;

    });

    $(document).off('click', 'div[name=delete]').on('click', 'div[name=delete]', function (e) {
        // console.log("删除元素")
        $(this).parents('div.layui-panel').remove();
        form.render();
        //页面删除元素时需要更新panel计数
        var examineType  = $view.find('select[name="examineType"]').find('option:selected').val();
        if(examineType=='5'){
            panelCount_project--;
        }else{
            panelCount_dept--;
        }
    });

    function initFormValue() {
        if (hazardExamineData) {
            form.val("hazardExamine-edit-form", {
                "examineId": hazardExamineData.examineId,
                "tenantId": hazardExamineData.tenantId,
                "examineNo": hazardExamineData.examineNo,
                "examineCategory": hazardExamineData.examineCategory,
                "examineType": hazardExamineData.examineType,
                "examineTitle": hazardExamineData.examineTitle,
                "startDate": hazardExamineData.startDate,
                "endDate": hazardExamineData.endDate,
                "objectId": hazardExamineData.objectId,
                "objectName": hazardExamineData.objectName,
                "remark": hazardExamineData.remark,
                "status": hazardExamineData.status,
            });
            $("#tenantId").val(hazardExamineData.tenantId==null?tenantId:hazardExamineData.tenantId);

            //加载检查项
            if(hazardExamineData.objectList && hazardExamineData.objectList.length>0){
                //检查类型
                let examineType = hazardExamineData.examineType;
                //检查项的序号从已有的length开始
                if(examineType=='1'){

                }else if(examineType=='5'){
                    //项目检查
                    panelCount_project = hazardExamineData.objectList.length;
                }else{
                    //部门、车间、班组检查
                    panelCount_dept = hazardExamineData.objectList.length;
                }
                let objectList = hazardExamineData.objectList;
                for(let i=0;i<objectList.length;i++){
                    appendHtml(i,objectList[i],examineType);
                }
            }

        }
    }

    function appendHtml(sort,item,examineType){
        let teamList = item.teamList;
        if(examineType =='1'){
            //公司检查
            $view.find("#company_field").show();
            $view.find("#company_box").show();
            if(teamList && teamList.length>0){
                reloadTab_company(teamList);
            }
        }else if(examineType =='5'){
            //项目检查
            $view.find("#project_field").show();
            $view.find("#company_field").hide();
            $view.find("#company_box").hide();
            //生成元素
            appendHtml_project(sort);
            //渲染数据
            renderData_project(sort,item);
        }else{
            //部门、车间、班组检查
            $view.find("#dept_field").show();
            $view.find("#company_field").hide();
            $view.find("#company_box").hide();
            //生成元素
            appendHtml_dept(sort,examineType);
            //渲染数据
            renderData_dept(sort,item);
        }
    }

    //拼接检查项（项目）
    function appendHtml_project(sort){
        var groupPanel_project = '<div class="layui-panel layui-panel-project" id="panel_project' + sort + '">' +
            '                        <div class="layui-field-box">' +
            '                            <div class="layui-form-item" >' +
            '                                <div class="layui-row">' +
            '                                    <div class="layui-col-md6">' +
            '                                        <label class="layui-form-label">项目名称：</label>' +
            '                                        <div class="layui-input-block">' +
            '                                            <select name="projectName" lay-filter="projectSelect' + sort + '" id="projectSelect' + sort + '">' +
            '                                                <option value="">请选择</option>' +
            '                                            </select>' +
            '                                        </div>' +
            '                                        </div>' +
            '                                    <div class="layui-col-md6">' +
            '                                        <div class="layui-input-block">' +
            '                                    <div class="layui-row layui-row-button">' +
            '                                       <div name="delete" class="layui-btn layui-btn-danger layui-btn-sm">' +
            '                                           <em class="layui-icon layui-icon-delete"></em> 删除信息' +
            '                                       </div>' +
            '                                    </div>' +
            '                                            </div>' +
            '                                    </div>' +
            '                                </div>' +
            '                            </div>' +
            '                            <div class="layui-form-item">' +
            '                                <div class="layui-row">' +
            '                                    <label class="layui-form-label">检查人员：</label>' +
            '                                    <div class="layui-input-block">' +
            '                                        <table lay-filter="groupUserTable_project" id="groupUserTable_project' + sort + '" lay-data="{id: \'groupUserTable_project\'' + sort + '}"></table>' +
            '                                    </div>' +
            '                                </div>' +
            '                            </div>' +
            '                            <div class="layui-form-item">' +
            '                                <div class="layui-row">' +
            '                                    <div class="layui-col-md12">' +
            '                                        <div class="layui-input-block">' +
            '                                            <button type="button" class="layui-btn layui-btn-sm" id="addRelation_project' + sort + '">' +
            '                                                <span class="layui-icon layui-icon-add-1" ></span>检查分组' +
            '                                            </button>' +
            '                                        </div>' +
            '                                    </div>' +
            '                                </div>' +
            '                            </div>' +
            '                        </div>' +
            '                    </div>';
        $("#project_box").append(groupPanel_project);
        //增加分组按钮
        addRelation_project("#addRelation_project"+sort,sort);
        //项目下拉框
        initProjectSelect($("#projectSelect"+sort),{tenantId:tenantId});
        //分组人员table
        initGroupUserTable($view.find('#groupUserTable_project'+sort),'groupUserTable_project'+sort,[]);
        form.render();
    }

    function renderData_project(sort,item){
        //项目下拉框
        $("#projectSelect"+sort).val(item.objectId);
        //分组人员table
        let teamList = item.teamList;
        if(teamList && teamList.length>0){
            initGroupUserTable($view.find('#groupUserTable_project'+sort),'groupUserTable_project'+sort,teamList);
        }
    }

    //拼接检查项（部门、车间、班组检查）
    function appendHtml_dept(sort,examineType){
        var label = '';
        if(examineType =='2'){
            label = '部门名称';
        }else if(examineType =='3'){
            label = '车间名称';
        }else if(examineType =='4'){
            label = '班组名称';
        }
        var groupPanel_dept = '<div class="layui-panel layui-panel-dept" id="panel_dept' + sort + '">' +
            '                        <div class="layui-field-box">' +
            '                            <div class="layui-form-item" >' +
            '                                <div class="layui-row">' +
            '                                    <div class="layui-col-md6">' +
            '                                        <label class="layui-form-label" id="deptNameLabel">'+label+'：</label>' +
            '                                        <div class="layui-input-block">' +
            '                                            <select name="deptId_deptExamine" lay-filter="deptId_deptExamine' + sort + '" id="deptId_deptExamine' + sort + '">' +
            '                                                <option value="">请选择</option>' +
            '                                            </select>' +
            '                                        </div>' +
            '                                    </div>' +
            '                                    <div class="layui-col-md6">' +
            '                                        <div class="layui-input-block">' +
            '                               <div class="layui-row layui-row-button">' +
            '                                   <div name="delete" class="layui-btn layui-btn-danger layui-btn-sm">' +
            '                                       <em class="layui-icon layui-icon-delete"></em> 删除信息' +
            '                                   </div>' +
            '                               </div>' +
            '                                        </div>' +
            '                                    </div>' +
            '                                </div>' +
            '                            </div>' +
            '                            <div class="layui-form-item">' +
            '                                <div class="layui-row">' +
            '                                    <label class="layui-form-label">检查人员：</label>' +
            '                                    <div class="layui-input-block">' +
            '                                        <table lay-filter="groupUserTable_dept" id="groupUserTable_dept' + sort + '" lay-data="{id: \'groupUserTable_dept\'' + sort + '}"></table>' +
            '                                    </div>' +
            '                                </div>' +
            '                            </div>' +
            '                            <div class="layui-form-item">' +
            '                                <div class="layui-row">' +
            '                                    <div class="layui-col-md12">' +
            '                                        <div class="layui-input-block">' +
            '                                            <button type="button" class="layui-btn layui-btn-sm" id="addRelation_dept' + sort + '">' +
            '                                                <span class="layui-icon layui-icon-add-1" ></span>检查分组' +
            '                                            </button>' +
            '                                        </div>' +
            '                                    </div>' +
            '                                </div>' +
            '                            </div>' +
            '                        </div>' +
            '                    </div>';
        $("#dept_box").append(groupPanel_dept);
        //增加分组按钮
        addRelation_dept("#addRelation_dept"+sort,sort);
        //部门下拉框
        initDeptSelect($("#deptId_deptExamine"+sort),{tenantId:tenantId});
        //分组人员table
        initGroupUserTable($view.find('#groupUserTable_dept'+sort),'groupUserTable_dept'+sort,[]);
        form.render();
    }

    function renderData_dept(sort,item){
        //部门下拉框
        $("#deptId_deptExamine"+sort).val(item.objectId);
        //分组人员table
        let teamList = item.teamList;
        if(teamList && teamList.length>0){
            initGroupUserTable($view.find('#groupUserTable_dept'+sort),'groupUserTable_dept'+sort,teamList);
        }
    }

    form.on('submit(hazardExamine-edit-form-save)', function (data) {
        data.field.status = '1';
        addOrUpdate(data.field,'保存');
        return false;
    });

    form.on('submit(hazardExamine-edit-form-submit)', function (data) {
        data.field.status = '2';
        addOrUpdate(data.field,'提交');
        return false;
    });

    function initDeptSelect(elem,data){
        elem.empty();
        febs.getSync(ctx + 'dept', data, function (r) {
            var deptList = r.data;
            var options = '';
            $.each(deptList,function (index,item) {
                var option =  '<option value="'+item.deptId+'">'+item.deptName+'</option>';
                options += option;
            })
            elem.append(options);
        });
        form.render();
    }

    function initProjectSelect(elem,data){
        elem.empty();
        febs.getSync(ctx + 'baseProject', data, function (r) {
            var projectList = r.data;
            var options = '';
            $.each(projectList,function (index,item) {
                var option =  '<option value="'+item.projectId+'">'+item.projectName+'</option>';
                options += option;
            })
            elem.append(options);
        });
        form.render();
    }

    form.on('select(tenantChoose)', function(obj){
        // 获取选中项 value
        var data={
            tenantId : obj.value
        }
        initDeptSelect(data);
    });

    formSelects.render();

    form.on('select(examineType)', function(obj){
        //部门、车间、班组检查序号重置
        panelCount_dept -= $view.find('div.layui-panel-dept').length;
        $view.find('div.layui-panel-dept').remove();

        //项目检查序号重置
        panelCount_project -= $view.find('div.layui-panel-project').length;
        $view.find('div.layui-panel-project').remove();
        var type = obj.value;
        if(type=='1'){
            $view.find("#company_box").show();
            $view.find("#company_field").show();
            $view.find("#dept_field").hide();
            $view.find("#project_field").hide();
        }else if(type=='5'){
            $view.find("#company_box").hide();
            $view.find("#company_field").hide();
            $view.find("#dept_field").hide();
            $view.find("#project_field").show();
        }else{
            $view.find("#company_box").hide();
            $view.find("#company_field").hide();
            $view.find("#dept_field").show();
            $view.find("#project_field").hide();
        }
        groupUserTableData_company=[];
        reloadTab_company(groupUserTableData_company);
    });


    function initProjectSelectArea(elem,sort){
        form.on('select(projectSelect'+sort+')', function(obj){
            elem.empty();
            formSelects.config('project-area-select'+sort, {
                searchUrl: ctx + 'baseProjectArea',
                data: {
                    projectId : obj.value,
                    tenantId : $("#tenantId").val()
                },
                response: {
                    statusCode: 200
                },
                beforeSuccess: function (id, url, searchVal, result) {
                    var data = result.data;
                    var tranData = [];
                    for (var i = 0; i < data.length; i++) {
                        tranData.push({
                            name: data[i].areaName,
                            value: data[i].areaId
                        })
                    }
                    result.data = tranData;
                    return result;
                },
                success: function () {
                    if(hazardExamineData && hazardExamineData.areaId != null){
                        formSelects.value('project-area-select'+sort, hazardExamineData.areaId.split(','));
                    }
                },
                error: function (id, url, searchVal, err) {
                    console.error(err);
                    febs.alert.error('获取区域列表失败');
                }
            });
            formSelects.render();

        });
    }

    function addOrUpdate(data,operation) {
        data.tenantId = $("#tenantId").val();
        //保存检查项信息
        data.objectList = saveObjectList();
        if (data.examineId && data.examineId.length > 0) {
            febs.modal.confirm(operation+'安全检查发布信息','确定'+operation+'安全检查发布信息？', function (index) {
                febs.postArray(ctx + 'hazardExamine/update', data, function () {
                    layer.closeAll();
                    febs.alert.success('修改成功');
                    $('#febs-hazardExamine').find('#query').trigger('click');
                });
            });
        } else {
            febs.modal.confirm(operation+'安全检查发布信息','确定'+operation+'安全检查发布信息？', function (index) {
                febs.postArray(ctx + 'hazardExamine', data, function () {
                    layer.closeAll();
                    febs.alert.success('新增成功');
                    $('#febs-hazardExamine').find('#query').trigger('click');
                });
            });

        }
    }
    function saveObjectList(){
        var objectList = [];
        // 检查类型
        var examineType  = $view.find('select[name="examineType"]').find('option:selected').val();
        if(examineType == '1'){
            //公司、综合检查
            $(".layui-panel-company").each(function (index, item) {
                var objectId = $view.find('select[name="tenantId"]').find('option:selected').val();
                var objectName = $view.find('select[name="tenantId"]').find('option:selected').text().trim();
                var groupUserList_company = layui.table.cache['groupUserTable_company'];
                objectList.push({
                    objectId: objectId,
                    objectName: objectName,
                    tenantId: $("#tenantId").val(),
                    teamList:groupUserList_company
                })
            })

        }else if(examineType =='5'){
            //项目检查
            $(".layui-panel-project").each(function (index, item) {
                var elemet = $(".layui-panel-project").eq(index);
                var objectId = elemet.find('select[name="projectName"]').find('option:selected').val();
                var objectName = elemet.find('select[name="projectName"]').find('option:selected').text();
                var groupUserList_project = layui.table.cache['groupUserTable_project'+index];
                objectList.push({
                    objectId: objectId,
                    objectName: objectName,
                    tenantId: $("#tenantId").val(),
                    teamList:groupUserList_project
                })
            })

        }else{
            // 部门、车间、班组检查
            $(".layui-panel-dept").each(function (index, item) {
                var elemet = $(".layui-panel-dept").eq(index);
                var objectId = elemet.find('select[name="deptId_deptExamine"]').find('option:selected').val();
                var objectName = elemet.find('select[name="deptId_deptExamine"]').find('option:selected').text();
                var groupUserList_dept = layui.table.cache['groupUserTable_dept'+index];
                objectList.push({
                    objectId: objectId,
                    objectName: objectName,
                    tenantId: $("#tenantId").val(),
                    teamList:groupUserList_dept
                })
            })
        }

        return objectList;
    }

    laydate.render({
        elem: "#startDate", done: function (value, date) {
            if ($("#endDate").val() && value > $("#endDate").val()) {
                febs.alert.warn('开始时间不能大于结束时间');
                $("#startDate").val("");
            }
        },
    });

    laydate.render({
        elem: "#endDate", done: function (value, date) {
            if ($("#startDate").val() && value < $("#startDate").val()) {
                febs.alert.warn('结束时间不能小于开始时间');
                $("#endDate").val("");
            }
        },
    });


});